module SessionsHelper
  def log_in(user)
    session[:user_id] = user.id
  end

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def logged_in?
    !current_user.nil?
  end


  def log_out
    session.delete(:user_id)
    session.delete(:company_id)
    session.delete(:studio_id)
    @current_user = nil
    @current_company = nil
    @current_studio = nil
  end

  def enter_company(company) 
    session[:company_id] = company.id
    #更新当前用户的公司
    current_user.update_attribute(:last_company_id, company.id)
  end

  def enter_studio(studio) 
    session[:studio_id] = studio.id 
    #更新当前用户的门店
    current_user.update_attribute(:last_studio_id, studio.id)
  end

  def current_studio
    @studio ||= Studio.find_by(id: session[:studio_id])
  end

  def current_company
    @company ||= Company.find_by(id: session[:company_id])
  end
end
